<?php

namespace backend\modules\business\controllers;

use backend\controllers\AdminController;
use common\models\business\BusinessPigPriceDetail;
use common\models\business\BusinessPigPriceType;
use common\models\business\BusinessPigPriceUnit;
use common\models\business\BusinessSaleorderDetail;
use Yii;
use common\models\business\BusinessSaleorder;
use backend\modules\business\models\BusinessSaleorderSearch;
use yii\db\Expression;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Response;

/**
 * SaleorderController implements the CRUD actions for BusinessSaleorder model.
 */
class SaleorderController extends AdminController
{


    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all BusinessSaleorder models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new BusinessSaleorderSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }



    /**
     * Displays a single BusinessSaleorder model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new BusinessSaleorder model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new BusinessSaleorder();
        $detailmodel = new BusinessSaleorderDetail();

        if(Yii::$app->request->isPost){

            if ($model->load(Yii::$app->request->post())) {
                if(!$model->save()){
                    return $this->dialog($this->checkError());
                }
            }

            $postdata = Yii::$app->request->post();

            if(!empty($postdata['type'])){
                $price = 0;
                foreach ($postdata['type'] as $key => $row){
                    //必要项没有填写的忽略
                    if(empty($row) || empty($postdata['price'][$key]) || empty($postdata['weight'][$key])){        //跳过
                        continue;
                    }

                    //订货单价格
                    $price +=  $postdata['totalprice'][$key];
                    $data = [
                        'name' => $row,
                        'saleorderid' => $model->id,
                        'price' => $postdata['price'][$key],
                        'weight' => $postdata['weight'][$key],
                        'pigid' => isset($postdata['pigid'])&&array_key_exists($key,$postdata['pigid'])?$postdata['pigid'][$key]:0,       //为0的是不取库存的
                        'pdid' => isset($postdata['pigid'])&&array_key_exists($key,$postdata['pdid'])?$postdata['pdid'][$key]:0,       //为0的是不取库存的
                        'unit' => $postdata['unit'][$key],
                        'remark' => $postdata['remark'][$key],
                        'createtime' => time(),
                        'totalprice' => $postdata['totalprice'][$key],
                    ];
                    $res = Yii::$app->db->createCommand()->insert(BusinessSaleorderDetail::tableName(),$data)->execute();
                }

                //保存价格
                $model->price += $price;
                $model->save();
            }
            return $this->redirect(['view', 'id' => $model->id]);
        } else {

            //分割类型
            $type = BusinessPigPriceType::find()->asArray()->all();
            //销售单位
            $unit = BusinessPigPriceUnit::find()->asArray()->all();
            return $this->render('create', [
                'model' => $model,
                'detailmodel' => $detailmodel,
                'type' => $type,
                'unit' => $unit
            ]);
        }
    }

    /**
     * Updates an existing BusinessSaleorder model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if(Yii::$app->request->isPost){

            if ($model->load(Yii::$app->request->post())) {
                if(!$model->save()){
                    return $this->dialog($this->checkError());
                }
            }

            $postdata = Yii::$app->request->post();

            $ids = Yii::$app->db->createCommand('select id from '.BusinessSaleorderDetail::tableName().' where saleorderid=:id')
                ->bindValues([':id'=>$id])
                ->queryAll();
            $ids = ArrayHelper::getColumn($ids,'id');


            $price = 0;
            if(!empty($postdata['type'])){
                foreach ($postdata['type'] as $key => $row){
                    //必要项没有填写的忽略
                    if(empty($row) || empty($postdata['price'][$key]) || empty($postdata['weight'][$key])){        //跳过
                        continue;
                    }
                    //订货单价格
                    $price +=  $postdata['totalprice'][$key];

                    $data = [
                        'name' => $row,
                        'saleorderid' => $id,
                        'price' => $postdata['price'][$key],
                        'weight' => $postdata['weight'][$key],
                        'pigid' => isset($postdata['pigid'])&&array_key_exists($key,$postdata['pigid'])?$postdata['pigid'][$key]:0,       //为0的是不取库存的
                        'pdid' => isset($postdata['pigid'])&&array_key_exists($key,$postdata['pdid'])?$postdata['pdid'][$key]:0,       //为0的是不取库存的
                        'unit' => $postdata['unit'][$key],
                        'remark' => $postdata['remark'][$key],
                        'createtime' => time(),
                        'totalprice' => $postdata['totalprice'][$key],
                    ];
                    $res = Yii::$app->db->createCommand()->insert(BusinessSaleorderDetail::tableName(),$data)->execute();
                }
                //保存价格
                $model->price += $price;
                $model->save();
            }

            //删除该删除的
            $nowids = array_key_exists('id',$postdata)?$postdata['id']:[];
            $diff = array_diff($ids,$nowids);
            if(is_array($diff) && !empty($diff)){
                $idstr = implode(',',$diff);
                Yii::$app->db->createCommand('delete from '.BusinessSaleorderDetail::tableName().' where id in ('.$idstr.')')
                    ->execute();
            }

            return $this->redirect(['view', 'id' => $model->id]);

        }  else {


            //分割类型
            $type = BusinessPigPriceType::find()->asArray()->all();
            //销售单位
            $unit = BusinessPigPriceUnit::find()->asArray()->all();

            $model->senddate = $model->senddate?date('Y-m-d',$model->senddate):'未送货';
            $model->paytime = $model->paytime?date('Y-m-d',$model->paytime):'未付款';

            return $this->render('update', [
                'model' => $model,
                'detailmodel' => $model->detail,
                'type' => $type,
                'unit' => $unit
            ]);
        }
    }

    /**
     * Deletes an existing BusinessSaleorder model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        if($model->status == BusinessSaleorder::IS_AGREE_AGREE){
            return $this->dialog('此单已经审核,不能删除！');
        }
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the BusinessSaleorder model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return BusinessSaleorder the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = BusinessSaleorder::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }


    /**
     * @param $id
     * @return string
     * 审核
     */
    public function actionAgree($id)
    {

        $data = [
            'agreeuser' => Yii::$app->user->identity->username,
            'agreetime' => time(),
            'isagree' => BusinessSaleorder::IS_AGREE_AGREE
        ];
        //更新订购单审核状态
        $res = Yii::$app->db->createCommand()->update(BusinessSaleorder::tableName(),$data,'id=:id',[':id'=>$id])
            ->execute();

        $dids = (new Query())->select('pdid')->from(BusinessSaleorderDetail::tableName())->where('saleorderid=:sid',[':sid'=>$id])->all();
        if(!empty($dids)){
            $dids = ArrayHelper::getColumn($dids,'pdid');
            $res = Yii::$app->db->createCommand()->update(BusinessPigPriceDetail::tableName(),['status'=>BusinessPigPriceDetail::STATUS_SELL],['id'=>$dids])
                ->execute();
        }

        return $res?$this->dialog('审核成功'):$this->dialog('审核失败');
    }


    /**
     *搜索库存
     */
    public function actionSearchKucun()
    {
        $this->layout = false;
        $type = Yii::$app->request->post('type');
        if(!$type){
            return '参数错误';
        }
        $hasid = Yii::$app->request->post('selid')?Yii::$app->request->post('selid'):[];
        $query = (new Query())->select('*')->from(['pd'=>BusinessPigPriceDetail::tableName()])
            ->where('type=:type and status=:status',[':type'=>$type,':status'=>BusinessPigPriceDetail::STATUS_DEFAULT])
            ->andWhere(['not exists',(new Query())->select('id')->from(['sd'=>BusinessSaleorderDetail::tableName()])->where('sd.pdid=pd.id')]);

        if(!empty($hasid)){
            $list = $query->andWhere(['not in','id',$hasid])->all();
        }else{
            $list = $query->all();
        }

        if(empty($list)){
            return '该类型没有可用的库存';
        }

        return $this->render('_kucun',[
            'list' => $list
        ]);
    }


    /**
     * @return array
     * 根据前端的选择的id返回对应的库存信息
     */
    public function actionGetkuinfo()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        $data = Yii::$app->request->post('data');
        if(empty($data)){
            return ['data'=>[],'status'=>0];
        }

        $totalprice = new Expression('convert((weight*price),decimal(10,2)) as totalprice');
        $list = (new Query())->select(['*',$totalprice])->from(BusinessPigPriceDetail::tableName())
            ->where(['id'=>$data])
            ->all();
       return $list;
    }



}
